<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Filter;

use Imagine\Gd\Imagine;
use Imagine\Image\Box;
use Imagine\Image\ImageInterface;
use Laminas\Filter\AbstractFilter;

/**
 * 图片缩微图
 * Class ImageThumb
 * @package Admin\Filter
 */
class ImageThumb extends AbstractFilter
{
    private $width  = 500;
    private $height = 500;
    private $mode   = ImageInterface::THUMBNAIL_INSET;
    private $rename = false;
    private $newName= '';

    public function __construct($options = [])
    {
        if(isset($options['width']))    $this->width    = $options['width'];
        if(isset($options['height']))   $this->height   = $options['height'];
        if(isset($options['mode']) && $options['mode'] == 'outbound') $this->mode = ImageInterface::THUMBNAIL_OUTBOUND;
        if(isset($options['rename']))   $this->rename   = $options['rename'];
        if(isset($options['newName']))  $this->newName  = $options['newName'];//如果是新命名，则原图会执行删除处理
    }

    public function filter($value)
    {
        $image = $value['tmp_name'];

        if($this->rename) {//判断缩微图是否重命名
            $thumbImagePath = dirname($image);
            $thumbImagePath = empty($thumbImagePath) ? '' : str_replace('.', '', $thumbImagePath) . '/';
            $thumbImageName = basename($image);
            $thumbImageNameArray = explode('.', $thumbImageName);
            $thumbImage     = $thumbImagePath . (!empty($this->newName) ? $this->newName : $thumbImageNameArray[0] . '_thumb') . '.' . $thumbImageNameArray[1];
            $value['thumbImage'] = $thumbImage;
        } else $thumbImage = $image;

        $imagine= new Imagine();
        $size   = new Box($this->width, $this->height);

        $imagine->open($image)->thumbnail($size, $this->mode)->save($thumbImage);
        if(!empty($this->newName)) @unlink($image);

        return $value;
    }
}